import axios from "axios";
import qs from "qs";
import { ElMessage } from 'element-plus';
import userStore from '../stores/userStore/index'
const http = axios.create({
  baseURL: "/api",
  timeout: 10000,
});


// HTTP状态码
http.httpcode = {
  SAVE_OK : 100011,
  DELETE_OK : 100021,
  UPDATE_OK : 100031,
  GET_OK : 100041,

  SAVE_ERR : 100010,
  DELETE_ERR : 100020,
  UPDATE_ERR : 100030,
  GET_ERR : 100040,

  SYSTEM_UNKOWN_ERR : 200000,
};

http.interceptors.request.use((config={}) => {
  // console.log(config.data)
  try {
    if (config.ContentType === "application/x-www-form-urlencoded") {
      config.data =
        config.data && qs.stringify(config.data, { indices: false });
    }
  } catch (e) {
    // console.log(e);
  }
  // console.log(config);
  return config;
});

http.interceptors.response.use(
  async (response) => {
    // HTTP响应状态码正常
    if (response.status === 200) {
      // nprogress.done();
      if ('code' in response.data) {
        const store = userStore();
        const data = response.data;
        switch (data.code) {
          case http.httpcode.SAVE_OK:
            return Promise.resolve(data);
          case http.httpcode.DELETE_OK:
            return Promise.resolve(data);
          case http.httpcode.UPDATE_OK:
            return Promise.resolve(data);
          case http.httpcode.GET_OK:
            return Promise.resolve(data);
          case http.httpcode.SAVE_ERR:
            return Promise.resolve(data);
          case http.httpcode.DELETE_ERR:
            return Promise.resolve(data);
          case http.httpcode.UPDATE_ERR:
            return Promise.resolve(data);
          case http.httpcode.GET_ERR:
            return Promise.resolve(data);
          default:
            // 显示操作失败提示
            // ElMessage.error(response.data.message || "操作失败!!!");
            return Promise.reject(data);
        }
      }
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  (error) => {
    if (error.code === 'ECONNABORTED' || error.code === 'ERR_NETWORK')
      sayError();
    return Promise.reject(error);
  }
);
function debounce (fn, delay) {
  let timer = null;
  return function (e) {
    if(timer){ clearTimeout(timer); }
    timer = setTimeout(()=>fn(e), delay);
  }
}
function sayError(){
debounce(ElMessage.error('连接服务器失败!!!'),1000)
}
export default function (method, url, submitData, ContentType) {
  let file
  switch (ContentType) {
    case "form":
      ContentType = "application/x-www-form-urlencoded";
      break;
    case "file":
      ContentType = "multipart/form-data";
      file = new FormData();
      file.append('file',submitData);
      submitData = file;
      break;
    case "files":
      ContentType = "multipart/form-data";
      file = new FormData();
      // console.log(submitData)
      for(let i = 0;i<submitData.length;i++) {
        file.append('file',submitData[i]);
      }
      submitData = file;
      break;
    case "rest":
      url+='/'+submitData;
      submitData=null;
      break;
    default:
      ContentType = "application/json";
  }
  return new Promise((resolve, reject) => {
    const reqParams = {
      method,
      url,
      [method.toLowerCase() === "get" //|| method.toLowerCase() === "delete"
        ? "params"
        : "data"]: submitData,
      ContentType,
      paramsSerializer: function (params) {
        return qs.stringify(params, { indices: false });
      },
    };
    http(reqParams)
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        // console.log(err);
        reject(err);
      });
  });
}
